<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/28 0028
 * Time: 11:15
 */

namespace app\admin\controller;


use think\Cache;
use think\Db;

class Currency extends Middle
{
    //todo 币种列表
    private $key = 'CurrencyList';

    public function CurrencyList(){
        $list = Db::name('currency')
                ->where(['pid'=>0])
                ->field('cu_id,title,show')
                ->select();
         if(!$list)return $this->returnError($this->NoData);
      	 foreach ($list as $k=>$v){
         $list[$k]['son'] = Db::name('currency')
          	->where(['pid'=>$v['cu_id'],'type'=>1])
          	->field('cu_id,title,show')
          	->select();
      	}
        return $this->returnSuccess($list);
    }

    //todo 币种设置
    public function CurrencySet(){
        $cu_id = isset($this->data['cu_id']) ? $this->data['cu_id'] :false;
        $type  = isset($this->data['type']) ? $this->data['type'] :1;
      	$show  = isset($this->data['show']) ? $this->data['show'] :1;
        $set = [
            'title' =>$this->data['title'],
            'pid'   =>$this->data['pid'],
            'show'  =>$show,
            'type'  =>$type,
        ];
        if($cu_id){
            $set['cu_id']   =$cu_id;
            $ref = Db::name('currency')->update($set);
        }else{
            $ref = Db::name('currency')->insert($set);
        }
        if(!$ref)return $this->returnError($this->Error);       
        $this->redis->delete('HeYueCurrency');
        return $this->returnSuccess('操作成功');
    }
    //todo 详情
    public function CurrencyDetail(){
        $map = ['cu_id'=>$this->data['cu_id']];
        $res = Db::name('currency')->where($map)->field('cu_id,pid,show,title')->find();
        if($res)return $this->returnSuccess($res);
        return $this->returnError($this->Error);
    }
    //todo 删除
    public function CurrencyDel(){
        $map = ['cu_id'=>$this->data['cu_id']];
        $cu_id = Db::name('currency')->where($map)->value('cu_id');
        if(!$cu_id)return $this->returnError($this->NoData);
        $son = Db::name('currency')->where(['pid'=>$cu_id])->count();
        if($son > 0 )return $this->returnError('请先删除该类下的币种');
        $ref = Db::name('currency')->delete($cu_id);
        if(!$ref)return $this->returnError($this->Error);
        return $this->returnSuccess('操作成功');

    }

    //todo 获取平台所以币种（去重）
    public function GetCurrency(){
        $list = Db::name('currency')
            ->where(['pid'=>['>',0],'type'=>1])
            ->field('title')
            ->group('title')
            ->select();
        return $this->returnSuccess($list);
    }
    //todo 首页币种设置
    public function WapSixSet(){
        $key = 'WapSixData';
        $res = $this->data['title'];
        $list = Cache::get($key);
        foreach ($list as $k){
            if($res == $k)return $this->returnError('已有相同币种');
        }
        array_push($list,$res);
        Cache::set($key,$list);
        return $this->returnSuccess('设置成功');
    }
    //todo 首页币种删除
    public function WapSixDel(){
        $key = 'WapSixData';
        $res = $this->data['title'];
        $list = Cache::get($key);
        foreach ($list as $k=>$v){
            if($res == $v){
                unset($list[$k]);
            };
        }
        Cache::set($key,$list);
        return $this->returnSuccess('操作成功');
    }

    //todo 合约币种
    public function CurrencyHeyueList(){
        $list = Db::name('currency')
            ->where(['cu_id'=>['in',[3,16]]])
            ->field('cu_id,title,show')
            ->select();
        if($list){
            foreach ($list as $k=>$v){
                $ref = Db::name('currency')
                    ->where(['pid'=>$v['cu_id'],'type'=>2])
                    ->field('cu_id,title,show')
                    ->select();
                $list[$k]['son'] = $ref;
            }
        }
        return $this->returnSuccess($list);
    }
    //todo 交易对测试
    public function CurrencyTest(){
        switch ($this->data['platform']){
            case 'ZB';
                $api = 'http://api.zb.cn/data/v1/kline?market='.$this->data['title'].'_usdt&size=1';
                $data = json_decode($this->cUrl($api));
                break;
            case 'Okex';
                $start = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()-3600*12));;
                $end   = str_replace(['+08:00',':'],['Z','%3A'],date(DATE_RFC3339_EXTENDED,time()));
                $api = 'https://www.okex.com/api/spot/v3/instruments/'.strtoupper($this->data['title']).'-USDT/candles?granularity=60&start='.$start.'&end='.$end;
                $data = json_decode($this->cUrl($api));
                break;
            case 'Huobi';
                $api = "https://api.huobi.pro/market/history/kline?period=60min&size=1&symbol=".$this->data['title']."usdt";
                $data = json_decode($this->cUrl($api));
                break;
            case 'BA';
                $api = 'https://api.binance.com/api/v3/ticker/price?symbol='.strtoupper($this->data['title']).'USDT';
                $data = json_decode($this->cUrl($api));
                break;
            case 'Gateio';
                $api = 'https://data.gateio.co/api2/1/candlestick2/'.$this->data['title'].'_usdt?group_sec=60&range_hour=0.01';
                $data = json_decode($this->cUrl($api));
                break;
            default;
                $data = 'api error';
                break;
        }
        return $this->returnSuccess($data);
    }
}